define([
    'jquery',
    'underscore',
    'backbone',
    'module/operation/models/OperationModel',
    'module/operation/models/OperationCollection',
    'module/operation/views/List',
    'text!module/operation/templates/main.html',
    'text!module/operation/templates/add.html',
    'text!module/operation/templates/edit.html',
    'text!module/operation/templates/drop.html',
    'text!module/operation/templates/read.html',
], function($, _, Backbone, OperationModel, OperationCollection, List, main, add, edit, drop, read) {

    var OperationController = Backbone.View.extend({
        el: $("#page"),
        initialize: function() {

            this.render();
            this.list_view();
        },
        events: {
            "click #list_view": "list_view",
            "click #add_view": "add_view",
            "click #read_view": "read_view",
            "click #edit_view": "edit_view",
            "click #drop_view": "drop_view",
            "click #add_article_view": "add_article_view",
            "click #add_action": "add_action",
            "click #edit_action": "edit_action",
            "click #drop_action": "drop_action",
            "click #drop_item": "drop_item",
            "click #report": "report",
            "click #search": "search",
            "click #pag": "pag_action"
        },
        render: function() {
            this.$el.html(main);
            $("#title").html(this.options.title);
        },
        list_view: function() {
            var self = this;
            $.ajax({
                url: 'server/api/operation/find_all/' + this.options.type + '/1',
                type: 'GET',
                dataType: "json",
                success: function(data) {
                    var collection = new OperationCollection(data.result);
                    var list = new List({collection: collection, count: data.count});
                    list.render();
                    $("#title_operator").html(self.options.title_operator);
                }
            });
        },
        add_view: function() {
            $("#main-list").html(add);
            $("#title_operator").html(this.options.title_operator);
            $('#date').datepicker({});
            $("#date").datepicker('setDate', new Date());
            autocomplete(this.options.type);
            dialog_add_item();
        },
        read_view: function(event) {
            $("#main-list").html(read);
            var id = event.target.getAttribute('index');
            var operation = new OperationModel({id: id});
            operation.fetch({
                success: function(data) {
                    data = data.toJSON();
                    $("#serie").val(data.header.serie);
                    $("#number").val(data.header.number);
                    $("#date").val(data.header.date);
                    $("#operator_name").val(data.header.name);
                    $("#operator_code").val(data.header.code);
                    $("#operator_address").val(data.header.address);
                    var total = 0;
                    $.each(data.details, function(index, detail) {
                        total = parseFloat(total) + (parseFloat(detail.price) * parseFloat(detail.quantity));
                        $("#tbl_list").append("<tr>"
                                + "<td>" + detail.name + "</td>"
                                + "<td style=\"text-align: center;\">" + detail.price + "</td>"
                                + "<td style=\"text-align: center;\">" + detail.quantity + "</td>"
                                + "<td style=\"text-align: center;\">" + CurrencyFormatted(parseFloat(detail.price) * parseFloat(detail.quantity)) + "</td>"
                                + "</tr>");
                    });
                    calculate(total);
                }
            });
        },
        edit_view: function(event) {
            $("#main-list").html(edit);
            var id = event.target.getAttribute('index');
            var operation = new OperationModel({id: id});

        },
        drop_view: function(event) {
            $("#main-list").html(drop);
            var id = event.target.getAttribute('index');
            var operation = new OperationModel({id: id});
            operation.fetch({
                success: function(data) {
                    data = data.toJSON();
                    $("#id").val(data.header.id);
                    $("#serie").val(data.header.serie);
                    $("#number").val(data.header.number);
                    $("#date").val(data.header.date);
                    $("#operator_name").val(data.header.name);
                    $("#operator_code").val(data.header.code);
                    $("#operator_address").val(data.header.address);
                    var total = 0;
                    $.each(data.details, function(index, detail) {
                        total = parseFloat(total) + (parseFloat(detail.price) * parseFloat(detail.quantity));
                        $("#tbl_list").append("<tr>"
                                + "<td>" + detail.name + "</td>"
                                + "<td style=\"text-align: center;\">" + detail.price + "</td>"
                                + "<td style=\"text-align: center;\">" + detail.quantity + "</td>"
                                + "<td style=\"text-align: center;\">" + CurrencyFormatted(parseFloat(detail.price) * parseFloat(detail.quantity)) + "</td>"
                                + "</tr>");
                    });
                    calculate(total);
                }
            });
        },
        add_action: function() {
            if (($("#serie").val()).length == 0 || !parseInt($("#serie").val())) {
                alert("Ingrese serie y debe ser numerico");
                return;
            }
            if (($("#number").val()).length == 0 || !parseInt($("#number").val())) {
                alert("Ingrese número y debe ser numerico");
                return;
            }
            var self = this;
            var details = [];
            $('#tbl_list tbody tr').each(function() {
                var detail = new Object();
                detail.article_id = $(this).find("td[tp='article_id']").attr("index");
                detail.price = $(this).find("td[tp='price']").html();
                detail.quantity = $(this).find("td[tp='quantity']").html();
                details.push(detail);
            });

            var operation = new OperationModel();
            var operationDetails = {
                serie: $("#serie").val(),
                number: $("#number").val(),
                date: $("#date").val(),
                operator_id: $("#operator_id").val(),
                type: this.options.type,
                subtotal: $("#subtotal").html(),
                tax: $("#tax").html(),
                total: $("#total").html(),
                details: details
            };
            operation.save(operationDetails, {
                success: function(data) {
                    self.list_view();
                }
            });
        },
        edit_action: function() {
            var self = this;
            var operation = new OperationModel();
            var operationDetails = {
                id: $("#id").val(),
                name: $("#name").val()
            };
            operation.save(operationDetails, {
                success: function(data) {
                    self.list_view();
                }
            });
        },
        drop_action: function() {
            var self = this;
            var operation = new OperationModel({
                id: $("#id").val()
            });
            operation.destroy({
                success: function(data) {
                    self.list_view();
                }
            });
        },
        search: function() {
            var search = $('#txt_search').val();
            $.ajax({
                url: 'server/api/operation/search/' + search,
                type: 'GET',
                dataType: "json",
                success: function(data) {
                    var collection = new OperationCollection(data.result);
                    var list = new List({collection: collection, count: data.count});
                    list.render();
                }
            });
        },
        pag_action: function(event) {
            var id = event.target.getAttribute('index');
            $.ajax({
                url: 'server/api/operation/find_all/' + this.options.type + '/' + id,
                type: 'GET',
                dataType: "json",
                success: function(data) {
                    var collection = new OperationCollection(data.result);
                    var list = new List({collection: collection, count: data.count});
                    list.render();
                    $("#title_operator").html(self.options.title_operator);
                }
            });
        },
        add_article_view: function() {
            $("#article_name").val("");
            $("#article_price").val("");
            $("#article_quantity").val("");
            $("#dialog-list-articles").dialog("open");
        },
        drop_item: function(event) {
            var tr = event.target.parentElement.parentElement;
            var subtotal_item = tr.children[3].innerHTML;
            var tt = tr.parentNode;
            tt.removeChild(tr);
            calculate(parseFloat(subtotal_item) * -1);
        },
        report: function(event) {
            jQuery('<form action="api/operation/report" method="post"></form>')
                    .appendTo('body').submit().remove();
            /*$.ajax({
             url: 'api/operation/report',
             type: 'POST',
             dataType: "pdf",
             success: function(data) {
             
             }
             });*/

        }
    });
    return OperationController;
});

function autocomplete(type) {
    var url = "";
    if (type == 1) {
        url = "server/api/article/search_pucharse/";
    }
    else if (type == 2) {
        url = "server/api/article/search_sale/";
    }


    $("#operator_name").autocomplete({
        minLength: 2,
        source: function(request, response) {
            $.ajax({
                url: "server/api/operator/search_name/" + type + "/" + $("#operator_name").val(),
                dataType: "json",
                data: {},
                success: function(data) {
                    response($.map(data.result, function(item) {
                        return {
                            label: item.name + ", RUC : " + item.code,
                            value: item.name,
                            id: item.id,
                            ruc: item.code,
                            address: item.address
                        }
                    }));
                }
            });
        },
        select: function(event, ui) {
            $("#operator_id").val(ui.item.id);
            $("#operator_code").val(ui.item.ruc);
            $("#operator_address").val(ui.item.address);
        },
        open: function() {
            $("#operator_id").val("");
        },
        close: function() {
            //$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });
    $("#operator_code").autocomplete({
        minLength: 2,
        source: function(request, response) {
            $.ajax({
                url: "server/api/operator/search_code/" + type + "/" + $("#operator_code").val(),
                dataType: "json",
                data: {},
                success: function(data) {
                    response($.map(data.result, function(item) {
                        return {
                            label: item.name + ", RUC : " + item.code,
                            value: item.code,
                            id: item.id,
                            name: item.name,
                            address: item.address
                        }
                    }));
                }
            });
        },
        select: function(event, ui) {
            $("#operator_id").val(ui.item.id);
            $("#operator_name").val(ui.item.name);
            $("#operator_address").val(ui.item.address);
        },
        open: function() {
            $("#operator_id").val("");
        },
        close: function() {
            //$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });
    $("#article_name").autocomplete({
        minLength: 1,
        source: function(request, response) {
            $.ajax({
                url: url + $("#article_name").val(),
                dataType: "json",
                data: {},
                success: function(data) {
                    response($.map(data.result, function(item) {
                        return {
                            label: item.name,
                            value: item.name,
                            id: item.id,
                            price: item.price
                        }
                    }));
                }
            });
        },
        select: function(event, ui) {
            $("#article_id").val(ui.item.id);
            $("#article_price").val(ui.item.price);

        },
        open: function() {
            //$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        close: function() {
            //$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });


}
function dialog_add_item() {
    $("#dialog-list-articles").dialog({
        width: 550,
        modal: true,
        autoOpen: false,
        buttons: {
            "Agregar": function() {
                $("#article_price").parent().parent().removeClass('error');
                $("#article_price").parent().children('.help-inline').remove();
                $("#article_quantity").parent().parent().removeClass('error');
                $("#article_quantity").parent().children('.help-inline').remove();
                if (!isNumber($("#article_price").val())) {
                    $("#article_price").parent().parent().addClass('error');
                    $("#article_price").parent().append("<span class=\"help-inline\">Ingrese Valor numerico</span>");
                    return;
                }
                if (!isNumber($("#article_quantity").val())) {
                    $("#article_quantity").parent().parent().addClass('error');
                    $("#article_quantity").parent().append("<span class=\"help-inline\">Ingrese Valor numerico</span>");
                    return;
                }

                $("#tbl_list").append("<tr>"
                        + "<td tp=\"article_id\" index=\"" + $("#article_id").val() + "\">" + $("#article_name").val() + "</td>"
                        + "<td tp=\"price\" style=\"text-align: center;\">" + CurrencyFormatted($("#article_price").val()) + "</td>"
                        + "<td tp=\"quantity\" style=\"text-align: center;\">" + $("#article_quantity").val() + "</td>"
                        + "<td tp=\"subtotal_item\"style=\"text-align: center;\">" + CurrencyFormatted(parseFloat($("#article_price").val()) * parseFloat($("#article_quantity").val())) + "</td>"
                        + "<td style=\"text-align: center;\"><button class=\"btn btn-info btn-mini\" id=\"drop_item\"><i class=\"icon-remove\"></i>Eliminar</button></td>"
                        + "</tr>")
                var total = CurrencyFormatted(parseFloat($("#article_price").val()) * parseFloat($("#article_quantity").val()))
                calculate(total);
                $(this).dialog("close");
            },
            Cancel: function() {
                $(this).dialog("close");
            }
        }
    });
}
function calculate(total) {
    $("#total").html(CurrencyFormatted(parseFloat($("#total").html()) + parseFloat(total)));
    $("#subtotal").html(CurrencyFormatted((parseFloat($("#total").html()) * 100) / 118));
    $("#tax").html(CurrencyFormatted(parseFloat($("#total").html()) - parseFloat($("#subtotal").html())));
}
function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) {
        i = 0.00;
    }
    var minus = '';
    if (i < 0) {
        minus = '-';
    }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) {
        s += '.00';
    }
    if (s.indexOf('.') == (s.length - 2)) {
        s += '0';
    }
    s = minus + s;
    return s;
}
